import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  // 全局状态
  state() {
    return {
      isAdmin: false,
      userInfo: null,
      sidebar: {
        opened: true // 侧边栏默认展开
      },
      tagsView: {
        cachedViews: []
      },
      selectedMenu: ''
    }
  },
  // 修改状态的方法（同步）
  mutations: {
    setAdmin(state) {
      state.isAdmin = true
    },
    setUser(state, user) {
      state.user = user
    },
    toggleSidebar(state) {
      state.sidebar.opened = !state.sidebar.opened
    },
    addCachedView(state, path) {
      console.log('添加了', path)
      state.tagsView.cachedViews.push(path)
    }
  },
  // 异步操作
  actions: {
    toggleSideBar({ commit }) {
      commit('toggleSidebar')
    },
    addCachedView({ commit, state }, path) {
      if (!state.tagsView.cachedViews.includes(path)) {
        commit('addCachedView', path)
      }
    }
  },
  // 计算属性（getter）
  getters: {
    sidebar: (state) => state.sidebar,
    isAdmin: (state) => state.isAdmin,
    userInfo: (state) => state.userInfo,
    cachedViews: (state) => state.tagsView.cachedViews,
    selectedMenu: (state) => state.selectedMenu
  }
})

export default store
